package cn.tedu.tmall.basic.service.impl;

import cn.tedu.tmall.basic.dao.cache.repository.IDistrictCacheRepository;
import cn.tedu.tmall.basic.dao.persist.repository.IDistrictRepository;
import cn.tedu.tmall.basic.service.IDistrictService;
import cn.tedu.tmall.common.pojo.po.DistrictSimplePO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DistrictServiceImpl implements IDistrictService {

    @Autowired
    private IDistrictRepository districtRepository;
    @Autowired
    private IDistrictCacheRepository districtCacheRepository;

    @Override
    public List<DistrictSimplePO> listByParent(Long parentId) {
        // return districtRepository.listByParent(parentId);
        return districtCacheRepository.listByParent(parentId);
    }

    @Override
    public void rebuildCache() {
        districtCacheRepository.deleteAll();

        Long parentId = 0L;
        List<DistrictSimplePO> districtList = districtRepository.listByParent(parentId);
        districtCacheRepository.saveList(parentId, districtList);

        callRecursion(districtList);
    }

    private void callRecursion(List<DistrictSimplePO> list) {
        for (DistrictSimplePO district : list) {
            Long id = district.getId();
            List<DistrictSimplePO> subList = districtRepository.listByParent(id);
            if (subList.size() > 0) {
                districtCacheRepository.saveList(id, subList);
                callRecursion(subList);
            }
        }
    }

}
